package ferp.android;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Html;
import android.text.Spanned;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import ferp.core.card.Card;
import ferp.core.game.Bid;
import ferp.core.player.Profile;

/**
 * User: olegs
 * Date: 05/05/12 20:24
 */
public class GUI
{
  public static String m2s(int mode)
  {
    switch (mode)
    {
      case View.MeasureSpec.AT_MOST: return "at most";
      case View.MeasureSpec.EXACTLY: return "exactly";
      default: return "unspecified";
    }
  }

  public static String m2s(int ws, int hs)
  {
    return GUI.m2s(ws) + ":" + View.MeasureSpec.getSize(ws) + "|" + GUI.m2s(hs) + ":" + View.MeasureSpec.getSize(hs);
  }


  // fonts
  public static class Font
  {
    public static final Typeface BOLD   = Typeface.create("Times New Roman", Typeface.BOLD);
    public static final Typeface NORMAL = Typeface.create("Times New Roman", Typeface.NORMAL);
  }

  // colors
  public static class Color
  {
    // default colors
    public static final int NORMAL    = 0xFF000000;
    public static final int DISABLE   = 0xFFAEAEAE;

    // preferences colors
    public static final int CATEGORY  = 0xFFFFFFFF;
    public static final int TITLE     = 0xFF000000;
    public static final int SUMMARY   = 0xFF000000;

    // watermark colors
    public static final int WATERMARK_POOL  = 0x448b8989;
    public static final int WATERMARK_TABLE = 0xFF8b8989;
  }

  public static final class FitText
  {
    // fit text in TextView according to provided height
    public static boolean byHeight(TextView tv, float h)
    {
      if (tv.getTextScaleX() != 1)
        tv.setTextScaleX(1);
      else
        if (h == tv.getTextSize())
          return false;

      // fit vertically
      tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, h);

      return true;
    }

    public static boolean byWeight(View view, TextView text)
    {
      LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)view.getLayoutParams();
      float ts = view.getMeasuredHeight() * lp.weight;

      return byHeight(text, ts);
    }

    // fit text in TextView according to view's dimensions and x/y factors
    public static boolean byFactors(TextView tv, float fx, float fy)
    {
      return byHeightAndWidth(tv, tv.getMeasuredHeight() * fy, tv.getMeasuredWidth() * fx);
    }

    // fit text in TextView according to provided width and height
    public static boolean byWidth(TextView tv, float w)
    {
      // fit horizontally (if needed)
      float mtw = tv.getPaint().measureText(tv.getText().toString());

      if (w < mtw)
      {
        tv.setTextScaleX(w / mtw);

        return true;
      }

      return false;
    }

    // fit text in TextView according to provided width and height
    public static boolean byHeightAndWidth(TextView tv, float h, float w)
    {
      boolean bh = byHeight(tv, h), bw = byWidth(tv, w);

      return bh || bw;
    }
  }

  // center one dimension of object with size 'size' between 'start' and 'end' points
  public static int center(int size, int start, int end)
  {
    return start + (end - start - size) / 2;
  }

/*
  public static boolean isLandscape(Activity activity)
  {
    Display display = activity.getWindowManager().getDefaultDisplay();
    Configuration conf = activity.getResources().getConfiguration();

    // obtain device's default orientation
    int defaultOrientation = (conf.orientation != Configuration.ORIENTATION_UNDEFINED && conf.orientation != Configuration.ORIENTATION_SQUARE) &&
                             (((display.getRotation() == Surface.ROTATION_0 || display.getRotation() == Surface.ROTATION_180) && conf.orientation == Configuration.ORIENTATION_LANDSCAPE) ||
                              ((display.getRotation() == Surface.ROTATION_90 || display.getRotation() == Surface.ROTATION_270) && conf.orientation == Configuration.ORIENTATION_PORTRAIT)) ?
                             Configuration.ORIENTATION_LANDSCAPE : Configuration.ORIENTATION_PORTRAIT;

    // is device in landscape orientation ?
    if (defaultOrientation == Configuration.ORIENTATION_LANDSCAPE)
      return (display.getRotation() == Surface.ROTATION_0 || display.getRotation() == Surface.ROTATION_180);

    return (display.getRotation() == Surface.ROTATION_90 || display.getRotation() == Surface.ROTATION_270);
  }
*/

  public static void setOrientation(Activity activity, Profile profile)
  {
    boolean landscape = profile != null && profile.isLandscape();

    Configuration config = new Configuration(activity.getBaseContext().getResources().getConfiguration());
    config.orientation = landscape ? Configuration.ORIENTATION_LANDSCAPE : Configuration.ORIENTATION_PORTRAIT;
    activity.getBaseContext().getResources().updateConfiguration(config, null);

    activity.setRequestedOrientation(landscape ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  }

  public static void removeGlobalOnLayoutListener(View view, ViewTreeObserver.OnGlobalLayoutListener listener)
  {
    // for API >= 16 removeOnGlobalLayoutListener() method must be used instead of removeGlobalOnLayoutListener()
    // consider adding if (android.os.Build.VERSION.SDK_INT >= 16)
    view.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
  }

  public static Spanned getColoredText(String prefix, String color, String text)
  {
    return Html.fromHtml(prefix + String.format(COLORED_TEXT_PATTERN, "\"" + color + "\"", text));
  }

  public static Spanned getColoredText(String color, String text)
  {
    return getColoredText("", color, text);
  }

  public static Spanned getColoredText(String color, long value)
  {
    return getColoredText(color, String.valueOf(value));
  }

  public static void toast(Context context, int resID)
  {
    toast(context, context.getResources().getString(resID));
  }

  public static void toast(Context context, int resID, int length)
  {
    toast(context, context.getResources().getString(resID), length);
  }

  public static void toast(Context context, String text)
  {
    toast(context, text, Toast.LENGTH_SHORT);
  }

  public static void toast(Context context, String text, int length)
  {
    Toast t = Toast.makeText(context, text, length);
    t.setGravity(Gravity.CENTER, 0, 0);

    TextView tv = (TextView)t.getView().findViewById(android.R.id.message);
    tv.setTypeface(Font.NORMAL);

    t.show();
  }

  public static void tryToDismissDialog(Activity activity, int id)
  {
    try
    {
      activity.dismissDialog(id);
    }
    catch (IllegalArgumentException e)
    {
      /* do nothing */
    }
  }

  public static int getBidColor(Bid bid)
  {
    return bid.isPlay() && !bid.isMisere() ? getSuitColor(bid.trump) : Color.NORMAL;
  }

  public static int getSuitColor(Card.Suit suit)
  {
    if (suit == Card.Suit.NONE)
      return Color.NORMAL;

    return suit == Card.Suit.SPADES || suit == Card.Suit.CLUBS ? android.graphics.Color.BLACK : android.graphics.Color.RED;
  }


  public static void recycle(Drawable d)
  {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
      recycle2(d);
  }

  public static void recycle(Activity a, int id)
  {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
    {
      ImageView iv = (ImageView)a.findViewById(id);

      if (iv != null)
      {
        recycle2(iv.getBackground());
        iv.setBackgroundDrawable(null);

        recycle2(iv.getDrawable());
        iv.setImageDrawable(null);
      }
    }
  }

  private final static String COLORED_TEXT_PATTERN = "<font color=%s>%s</font>";

/*
  private static double screenInches(WindowManager wm)
  {
    DisplayMetrics dm = new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(dm);

    return Math.sqrt(Math.pow(dm.widthPixels / dm.densityDpi, 2) + Math.pow(dm.heightPixels / dm.densityDpi, 2));
  }
*/

  private static void recycle2(Drawable d)
  {
    if (d != null && d instanceof BitmapDrawable)
    {
      Bitmap b = ((BitmapDrawable)d).getBitmap();

      if (b != null && !b.isRecycled())
        b.recycle();
    }
  }
}


